package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManagerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@SuppressWarnings("all")
public class ManagerServiceImpl implements ManagerService {

    //自动注入
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     获取一级分类列表数据

     */
    @Override
    public List<BaseCategory1> getCategory1() {

        //调用mapper层的方法操作base_category1表的数据，实现查询一级分类列表的功能
        List<BaseCategory1> baseCategory1List = baseCategory1Mapper.selectList(null);
        return baseCategory1List;
    }

    /**
     获取二级分类数据

     */
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {

        LambdaQueryWrapper<BaseCategory2> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategory2::getCategory1Id,category1Id);

        /*QueryWrapper<BaseCategory2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category1_id",category1Id);*/

        return baseCategory2Mapper.selectList(queryWrapper);
    }

    /**
     获取三级分类数据

     */
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {

        LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategory3::getCategory2Id,category2Id);

        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(queryWrapper);

        return baseCategory3List;
    }

    /**
     根据分类ID 获取平台属性集合

     */
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);
        return baseAttrInfoList;
    }

    /**
     保存-修改平台属性
     * 区别：是否存在id
     *  修改首先回显的，有id
     *  保存，id不存在

     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        //判断分辨是保存还是修改
        if (baseAttrInfo.getId() != null) {
            //修改平台属性
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //删除平台属性值
            /*QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id",baseAttrInfo.getId());*/
            LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            baseAttrValueMapper.delete(queryWrapper);
        }else {

            //添加平台属性
            baseAttrInfoMapper.insert(baseAttrInfo);
        }

        //获取平台属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //判断
        if (!CollectionUtils.isEmpty(attrValueList)) {

            //保存平台属性值
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //添加属性id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }

    }

    /**
     根据平台属性ID 获取到平台属性值集合

     */
    @Override
    public BaseAttrInfo getAttrValueList(Long attrId) {

        //根据id查询属性对象
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);

        //查询平台属性值集合
        LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseAttrValue::getAttrId,attrId);

        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(queryWrapper);

        //判断
        if (baseAttrInfo != null) {

            baseAttrInfo.setAttrValueList(baseAttrValueList);
        }


        return baseAttrInfo;
    }

    /**
     查询Spu商品列表

     */
    @Override
    public IPage<SpuInfo> getSpuPageList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        //创建查询条件对象 where category3_id =?
        LambdaQueryWrapper<SpuInfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuInfo::getCategory3Id,spuInfo.getCategory3Id());
        queryWrapper.orderByDesc(SpuInfo::getId);


        IPage<SpuInfo> spuInfoIPage = spuInfoMapper.selectPage(spuInfoPage, queryWrapper);

        return spuInfoIPage;
    }

    /**
     获取销售属性数据

     */
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    /**
     保存spuInfo
     * spu_info
     * spu_sale_attr
     * spu_sale_attr_value
     * spu_images
     * spu_poster
     *
     * 问题：维护一个spuInfo的完整信息需要哪几张表

     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {

        //保存spuInfo
        spuInfoMapper.insert(spuInfo);

        //保存销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {

                //设置spuId
                spuSaleAttr.setSpuId(spuInfo.getId());

                spuSaleAttrMapper.insert(spuSaleAttr);

                //保存spuSaleAttrValue
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {

                        //设置spuId
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        //设置属性名称
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }

            }

        }

        //保存spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断
        if (!CollectionUtils.isEmpty(spuImageList)) {
            for (SpuImage spuImage : spuImageList) {

                //设置spuId
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }

        //保存spu_poster
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        //判断
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            for (SpuPoster spuPoster : spuPosterList) {

                //设置spuId
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            }
        }


    }

    /**
     根据spuId 获取spuImage 集合

     */
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        //构建条件查询器
        QueryWrapper<SpuImage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);

        return spuImageMapper.selectList(queryWrapper);
    }

    /**
     根据spuId 查询销售属性

     */
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    /**
     保存skuInfo
     *  sku_info
     *  sku_image
     *  sku_sale_attr_value
     *  sku_attr_value

     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {

        //保存skuInfo
        skuInfoMapper.insert(skuInfo);

        //保存平台属性值
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        //判断
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {

            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }

        //保存销售属性
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        //判断
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {

                //设置skuid
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                //设置spuid
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());

                skuSaleAttrValueMapper.insert(skuSaleAttrValue);

            }
        }

        //保存图片
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        //判断
        if(!CollectionUtils.isEmpty(skuImageList)){

            for (SkuImage skuImage : skuImageList) {

                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }


    }

    /**
     分页查询skuInfo

     */
    @Override
    public IPage<SkuInfo> getSkuListByPage(Page<SkuInfo> skuInfoPage) {
        Page<SkuInfo> skuInfoPage1 = skuInfoMapper.selectPage(skuInfoPage, new QueryWrapper<SkuInfo>().orderByDesc("id"));

        return skuInfoPage1;
    }

    /**
     商品上架

     */
    @Override
    public void onSale(Long skuId) {

        SkuInfo skuInfo=new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);

        skuInfoMapper.updateById(skuInfo);

    }

    /**
     商品下架

     */
    @Override
    public void cancelSale(Long skuId) {

        SkuInfo skuInfo=new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);

        skuInfoMapper.updateById(skuInfo);

    }

    /**
     根据skuId获取SkuInfo

     实现性能优化--缓存实现

     1、从Redis中获取数据
     有数据，直接返回
     没数据：
     2、先获取锁：
     没获取到锁：自旋
     获取到锁：
     3、查询数据:
     没有数据，存储null值，返回数据
     有数据，存储查询的数据，返回数据

     4、释放锁

     技术实现：1、基于redis直接实现
     2、基于redisson实现

     */
    @Override
    @GmallCache(prefix = "sku:",suffix = ":info")
    public SkuInfo getSkuInfo(Long skuId) {

        //redisson实现
//        return getSkuInfoRedisson(skuId);
        //redis实现
//        return getSkuInfoRedis(skuId);

        //查询数据库
        return getSkuInfoDB(skuId);
    }


    /**
     redisson实现

     */
    private SkuInfo getSkuInfoRedisson(Long skuId){

        try{
            //定义key sku:21:info
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;

            //尝试redis中获取数据
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断
            if (skuInfo == null) {
                //定义锁key
                String skuLock=RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //获取锁
                RLock lock = redissonClient.getLock(skuLock);
                //加锁
                boolean flag = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断
                if(flag){ //获取到了锁

                    try{
                        skuInfo = this.getSkuInfoDB(skuId);
                        //判断
                        if (skuInfo != null) {
                            //存储到redis 返回
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;
                        }else {
                            //存储null--避免缓存穿透
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;
                        }


                    }finally {
                        //释放锁
                        lock.unlock();

                    }

                }else {

                    try {
                        Thread.sleep(100);
                        return getSkuInfoRedisson(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }else {
                //缓存有数据
                return skuInfo;
            }


        }catch (Exception e){
            e.printStackTrace();

        }

        return this.getSkuInfoDB(skuId);
    }


    /**
     redis实现分布式锁

     */
    private SkuInfo getSkuInfoRedis(Long skuId){

        try{
            //定义key sku:21:info
            String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;

            //尝试redis中获取数据
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            //判断
            if (skuInfo == null) {//缓存中没有数据

                //定义锁值
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                //定义锁的key sku:21:lock sku:22:lock
                String skuLock = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;

                //获取锁
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(skuLock, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断
                if (flag) {//获取到了锁

                    try{
                        //查询数据库
                        skuInfo = this.getSkuInfoDB(skuId);
                        //判断
                        if (skuInfo != null) {
                            //存储到redis ，返回
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;
                        }else {
                            //存储null--避免缓存穿透
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;
                        }

                    }finally {
                        //释放锁
                        //定义脚本
                        String script="if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                                "then\n" +
                                "    return redis.call(\"del\",KEYS[1])\n" +
                                "else\n" +
                                "    return 0\n" +
                                "end";

                        //创建脚本对象
                        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                        //设置脚本
                        redisScript.setScriptText(script);
                        //设置返回类型
                        redisScript.setResultType(Long.class);

                        //执行释放锁
                        redisTemplate.execute(redisScript,Arrays.asList("lock"),uuid);
                    }
                }else {
                    //没有获取到锁
                    try{
                        //自旋
                        Thread.sleep(100);
                        return getSkuInfoRedis(skuId);

                    }catch (Exception e){

                        e.printStackTrace();
                    }
                }


            }else {

                //说明缓存中有值，直接返回
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //兜底的方法
        return this.getSkuInfoDB(skuId);
    }


    /**
     获取skuInfo查询数据库

     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        //查询skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //构建条件对象
        LambdaQueryWrapper<SkuImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuImage::getSkuId,skuId);

        //查询关联的图片信息
        List<SkuImage> skuImages = skuImageMapper.selectList(queryWrapper);
        //判断
        if (skuInfo != null) {
            skuInfo.setSkuImageList(skuImages);
        }
        return skuInfo;

    }

    /**
     根据skuId 获取最新的商品价格

     */
    @Override
    public BigDecimal getSkuPrice(Long skuId) {

        //获取锁
        RLock lock = redissonClient.getLock(skuId + ":lock");

        //加锁
        lock.lock();

        try {
            SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
            //判断
            if (skuInfo != null) {

                return skuInfo.getPrice();
            }
        }finally {

            lock.unlock();
        }

        return new BigDecimal("0");
    }

    /**
     根据三级分类id 获取分类信息

     */
    @Override
    @GmallCache(prefix = "baseCategoryView:",suffix = ":info")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     根据spuId 获取海报数据

     */
    @Override
    @GmallCache(prefix = "findSpuPosterBySpuId:",suffix = ":info")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        //构建构造器
        QueryWrapper<SpuPoster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);

        //执行查询
        return spuPosterMapper.selectList(queryWrapper);


    }

    /**
     根据skuId 获取平台属性数据

     */
    @Override
    @GmallCache(prefix = "attrList:",suffix = ":info")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectAttrList(skuId);
    }

    /**
     根据spuId,skuId 获取销售属性数据

     */
    @Override
    @GmallCache(prefix = "spuSaleAttrListCheckBySk:",suffix = ":info")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return  spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    /**
     根据spuId 获取到销售属性值Id 与skuId 组成的数据集

     */
    @Override
    @GmallCache(prefix = "skuValueIdsMap:",suffix = ":info")
    public Map getSkuValueIdsMap(Long spuId) {

        Map resultMap = new HashMap();

        List<Map> listMap = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        //判断
        if(!CollectionUtils.isEmpty(listMap)){

            for (Map map : listMap) {
                resultMap.put(map.get("value_ids"),map.get("sku_id"));
            }
        }

        return resultMap;

    }

    /**
     获取首页分类数据

     */
    @Override
    @GmallCache(prefix = "baseCategoryList:",suffix = ":info")
    public List<JSONObject> getBaseCategoryList() {

        //创建集合封装数据
        List<JSONObject> category1List=new ArrayList<>();

        //查询所有分类数据
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);

        //判断
        if(!CollectionUtils.isEmpty(baseCategoryViewList)){

            int index=1;
            //分组处理一级分类
            Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
            //处理map
            for (Map.Entry<Long, List<BaseCategoryView>> entry : category1Map.entrySet()) {

                //创建封装对象
                JSONObject category1=new JSONObject();
                category1.put("index",index++);
                //获取一级分类的id
                Long category1Id = entry.getKey();
                category1.put("categoryId",category1Id);
                //获取一级分类的数据
                List<BaseCategoryView> categorg2List = entry.getValue();
                //获取一级分类name
                String category1Name = categorg2List.get(0).getCategory1Name();
                category1.put("categoryName",category1Name);
                ///处理二级分类
                Map<Long, List<BaseCategoryView>> category2Map = categorg2List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));


                //创建二级分类封装的集合
                List<JSONObject> list2Category=new ArrayList<>();
                //处理二级分类分组数据
                for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {

                    JSONObject category2=new JSONObject();
                    //获取二级分类id
                    Long category2Id = entry2.getKey();
                    category2.put("categoryId",category2Id);
                    //获取三级分类数据集合
                    List<BaseCategoryView> categorg3List = entry2.getValue();
                    //获取二级分类的名称
                    String category2Name = categorg3List.get(0).getCategory2Name();
                    category2.put("categoryName",category2Name);

                    List<JSONObject> list3Category=new ArrayList<>();
                    //处理三级分类
                    for (BaseCategoryView baseCategoryView : categorg3List) {

                        JSONObject category3=new JSONObject();
                        //获取三级分类id
                        Long category3Id = baseCategoryView.getCategory3Id();
                        category3.put("categoryId",category3Id);
                        //获取三级分类name
                        String category3Name = baseCategoryView.getCategory3Name();
                        category3.put("categoryName",category3Name);
                        list3Category.add(category3);

                    }

                    //category2设置三级分类集合
                    category2.put("categoryChild",list3Category);

                    list2Category.add(category2);



                }

                //一级分类收集二级分类集合
                category1.put("categoryChild",list2Category);


                //设置到外层集合
                category1List.add(category1);

            }



        }


        return category1List;
    }

    /**
     * 获取一级分类列表数据
     *//*
    @Override
    public List<BaseCategory1> getCategory1() {


        //调用Mapper层方法 操作数据库
        List<BaseCategory1> baseCategory1List = baseCategory1Mapper.selectList(null);

        return baseCategory1List;
    }

    *//**
     * 获取二级分类数据
     *//*

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {

        QueryWrapper<BaseCategory2> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category1_id", category1Id);

        //调用Mapper层中的方法,用于操作baseCategory2 表中的数据
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(queryWrapper);

        return baseCategory2List;
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {

        //调用Mapper中的方法，操作base_category3表中的数据
        //select * from base_category3 where category2Id = ?
        LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategory3::getCategory2Id, category2Id);
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(queryWrapper);

        return baseCategory3List;
    }

    *//**
     * 根据分类ID 获取属性集合
     *//*
    @Override

    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {



        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    *//**
     * 保存-修改平台属性
     *//*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        //判断是保存还是修改
        if (baseAttrInfo.getId() != null) {
            //修改平台属性
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //删除平台属性值
            //delete from base_attr_value where attr_id = id
            QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", baseAttrInfo.getId());
            baseAttrValueMapper.delete(queryWrapper);


        } else {

            //添加平台属性
            baseAttrInfoMapper.insert(baseAttrInfo);
        }


        //获取平台属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //判断
        if (!CollectionUtils.isEmpty(attrValueList)) {

            //保存平台属性值
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //添加属性id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);

            }


        }


    }

    *//**
     * 根据平台属性Id 获取到平台属性值集合
     *//*
    @Override
    public BaseAttrInfo getAttrValueList(Long attrId) {

        //根据id查询属性对象
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);

        //查询平台属性值集合
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", attrId);
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(queryWrapper);

        //判断
        if (baseAttrInfo != null) {

            baseAttrInfo.setAttrValueList(baseAttrValueList);
        }

        return baseAttrInfo;
    }


    *//**
     * 查询spu列表
     *
     * @param spuInfoPage
     * @param spuInfo
     * @return
     *//*
    @Override
    public IPage<SpuInfo> getSpuPageList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {


        //创建查询条件对象 where category3_id =?
        LambdaQueryWrapper<SpuInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuInfo::getCategory3Id, spuInfo.getCategory3Id());
        queryWrapper.orderByDesc(SpuInfo::getId);


        IPage<SpuInfo> spuInfoIPage = spuInfoMapper.selectPage(spuInfoPage, queryWrapper);

        return spuInfoIPage;
    }

    *//**
     * 获取销售属性数据
     *
     * @return
     *//*
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    *//**
     * 保存spuInfo
     * spu_info
     * spu_sale_attr
     * spu_sale_attr_value
     * spu_images
     * spu_poster
     * <p>
     * 问题：维护一个spuInfo的完整信息需要哪几张表
     *//*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {

        //保存spuInfo
        spuInfoMapper.insert(spuInfo);
        //保存销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //判断
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {

            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {

                //设置spuId
                spuSaleAttr.setSpuId(spuInfo.getId());

                spuSaleAttrMapper.insert(spuSaleAttr);

                //保存spuSaleAttrValue
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //判断
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {

                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {

                        //设置spuId
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        //设置属性名称
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }

                }

            }

        }

        //保存spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断
        if (!CollectionUtils.isEmpty(spuImageList)) {

            for (SpuImage spuImage : spuImageList) {

                //设置spuId
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }

        //保存spu_poster
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        //判断
        if (!CollectionUtils.isEmpty(spuPosterList)) {

            for (SpuPoster spuPoster : spuPosterList) {

                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);

            }
        }

    }

    *//**
     * 根据spuId 获取spuImage 集合
     * @param spuId
     * @return
     *//*
    @Override
    public List<SpuImage> spuImageList(Long spuId) {

        //构建条件查询器
        QueryWrapper<SpuImage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);

        return spuImageMapper.selectList(queryWrapper);
    }

    *//**
     * 根据spuId 查询销售属性
     * @param spuId
     * @return
     *//*
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {


        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);

    }

    *//**
     * 保存skuInfo
     *  sku_info
     *  sku_image
     *  sku_sale_attr_value
     *  sku_attr_value
     *
     *
     * @param skuInfo
     *//*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {

        //保存skuInfo
        skuInfoMapper.insert(skuInfo);

        //保存平台属性值
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        //判断
        if(!CollectionUtils.isEmpty(skuAttrValueList)){

            for (SkuAttrValue skuAttrValue : skuAttrValueList) {

                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }


        }


        //保存销售属性值
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        //判断
        if(!CollectionUtils.isEmpty(skuSaleAttrValueList)){

            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {

                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());

                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }

        //保存图片
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        //判断
        if(!CollectionUtils.isEmpty(skuImageList)){

            for (SkuImage skuImage : skuImageList) {

                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }

//        //存储到布隆过滤器标记
//        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
//        //存储
//        bloomFilter.add(skuInfo.getId());



    }

    *//**
     * 分页查询skuInfo
     * @param skuInfoPage
     * @return
     *//*
    @Override
    public IPage<SkuInfo> getSkuListByPage(Page<SkuInfo> skuInfoPage) {

        Page<SkuInfo> skuInfoPage1 = skuInfoMapper.selectPage(skuInfoPage, new QueryWrapper<SkuInfo>().orderByDesc("id"));

        return skuInfoPage1;
    }

    *//**
     * 商品上架
     * @param skuId
     *//*
    @Override
    public void onSale(Long skuId) {

        SkuInfo skuInfo=new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);

        skuInfoMapper.updateById(skuInfo);

    }

    *//**
     * 商品下架
     * @param skuId
     *//*
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo=new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);

        skuInfoMapper.updateById(skuInfo);
    }

    *//**
     * 根据skuId获取SkuInfo
     * @param skuId
     * @return
     *
     * 实现性能优化--缓存实现
     *
     * 1.从redis中获取数据
     *    有：直接返回
     *    没有：
     *    2.获取锁
     *       没获取到：自旋
     *       获取到
     *       3.查询数据
     *          没有：存储null值，返回数据
     *          有：存储查询的数据，返回数据
     *
     *       4.释放锁
     *
     *技术实现：
     *     1.基于redis直接实现
     *     2.基于redisson实现
     *
     *
     *
     *//*

    @Override
    @GmallCache(prefix="sku:",suffix=":info")
    public SkuInfo getSkuInfo(Long skuId) {

        //redisson实现
//        return getSkuInfoRedisson(skuId);
        //redis实现
//        return getSkuInfoRedis(skuId);

        //查询数据库
        return getSkuInfoDB(skuId);
    }




    @Autowired
    private RedissonClient redissonClient;
    *//**
     * redisson实现
     * @param skuId
     * @return
     *//*
    private SkuInfo getSkuInfoRedisson(Long skuId) {
        try {
            //定义key sku:21:info
            String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;

            //尝试redis中获取数据
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断
            if(skuInfo==null){
                //定义锁key
                String skuLock=RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //获取锁
                RLock lock = redissonClient.getLock(skuLock);
                //加锁
                boolean flag = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断
                if(flag){ //获取到了锁

                    try {
                        skuInfo = this.getSkuInfoDB(skuId);
                        //判断
                        if(skuInfo!=null){
                            //存储到redis，返回
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);

                            return skuInfo;
                        }else{
                            //存储null--避免缓存穿透
                            skuInfo =new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;

                        }
                    } finally {
                        //释放锁
                        lock.unlock();
                    }




                }else {

                    try {
                        Thread.sleep(100);
                        return getSkuInfoRedisson(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }else{
                //缓存有数据
                return skuInfo;


            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return this.getSkuInfoDB(skuId);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    *//**
     * redis实现分布式锁
     *
     * @param skuId
     * @return
     *//*
    private SkuInfo getSkuInfoRedis(Long skuId) {

        try {
            //定义key sku:21:info
            String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;

            //尝试redis中获取数据
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            //判断
            if(skuInfo==null){  //缓存中没有数据

                //定义锁值
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //定义锁的key sku:21:lock  sku:22:lock
                String skuLock=RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;

                //获取锁
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(skuLock, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断
                if(flag){//获取到了锁

                    try {
                        //查询数据库
                        skuInfo = this.getSkuInfoDB(skuId);
                        //判断
                        if(skuInfo!=null){
                            //存储到redis，返回
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;
                        }else{
                            //存储null--避免缓存穿透
                            skuInfo =new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SECKILL__TIMEOUT,TimeUnit.SECONDS);

                            return skuInfo;

                        }
                    } finally {
                        //释放锁
                        //定义脚本
                        String script="if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                                "then\n" +
                                "    return redis.call(\"del\",KEYS[1])\n" +
                                "else\n" +
                                "    return 0\n" +
                                "end";

                        //创建脚本对象
                        DefaultRedisScript<Long> redisScript=new DefaultRedisScript<>();
                        //设置脚本
                        redisScript.setScriptText(script);
                        //设置返回类型
                        redisScript.setResultType(Long.class);

                        //执行释放锁
                        redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);

                    }




                }else{
                    //没有获取到锁
                    try {
                        //自旋
                        Thread.sleep(100);
                        return getSkuInfoRedis(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }else {

                //说明缓存中有值，直接返回
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //兜底的方法
        return this.getSkuInfoDB(skuId);
    }




    *//**
     * 获取skuInfo查询数据库
     * @param skuId
     * @return
     *//*
    private SkuInfo getSkuInfoDB(Long skuId) {
        //查询skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //构建条件对象
        LambdaQueryWrapper<SkuImage> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SkuImage::getSkuId,skuId);
        //查询关联的图片信息
        List<SkuImage> skuImages = skuImageMapper.selectList(queryWrapper);
        //判断
        if(skuInfo!=null){

            skuInfo.setSkuImageList(skuImages);
        }
        return skuInfo;
    }

    *//**
     * 根据skuId 获取最新的商品价格
     * @param skuId
     * @return
     *//*
    @Override
    public BigDecimal getSkuPrice(Long skuId) {

        //获取锁
        RLock lock = redissonClient.getLock(skuId + ":lock");
        //加锁
        lock.lock();

        try {
            SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
            //判断
            if(skuInfo!=null){

                return skuInfo.getPrice();
            }
        } finally {

            lock.unlock();
        }


        return new BigDecimal("0");
    }

    *//**
     * 根据三级分类id获取分类信息
     * @param category3Id
     * @return
     *//*
    @Override
    @GmallCache(prefix="baseCategoryView:",suffix=":info")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    *//**
     * 根据spuId 获取海报数据
     * @param spuId
     * @return
     *//*
    @Override
    @GmallCache(prefix="findSpuPosterBySpuId:",suffix=":info")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        //构建查询器
        QueryWrapper<SpuPoster> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        //执行查询
        return spuPosterMapper.selectList(queryWrapper);
    }

    *//**
     * 根据skuId 获取平台属性数据
     * @param skuId
     * @return
     *//*
    @Override
    @GmallCache(prefix="attrList:",suffix=":info")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectAttrList(skuId);
    }

    *//**
     * 根据spuId,skuId 获取销售属性数据
     * @param skuId
     * @param spuId
     * @return
     *//*
    @Override
    @GmallCache(prefix="spuSaleAttrListCheckBySk:",suffix=":info")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {



        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    *//**
     * 根据spuId 获取到销售属性值Id 与skuId 组成的数据集
     * @param spuId
     *
     *//*
    @Override
    @GmallCache(prefix="skuValueIdsMap:",suffix=":info")
    public Map getSkuValueIdsMap(Long spuId) {

        Map resultMap=new HashMap();

        List<Map> listMap=skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        //判断
        if(!CollectionUtils.isEmpty(listMap)){

            for (Map map : listMap) {
                resultMap.put(map.get("value_ids"),map.get("sku_id"));
            }
        }

        return resultMap;
    }*/

}
